import { getAllCards } from '../data/tarotCards.js';

// 塔罗牌管理类 - 实现洗牌、抽牌和共时性原理
export class TarotDeck {
  constructor() {
    this.cards = [...getAllCards()];
    this.drawnCards = [];
    this.isShuffled = false;
    this.shuffleCount = 0;
  }

  // 洗牌功能 - 模拟共时性原理中的随机性
  shuffle() {
    // 使用Fisher-Yates洗牌算法
    for (let i = this.cards.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [this.cards[i], this.cards[j]] = [this.cards[j], this.cards[i]];
    }
    
    // 增加洗牌次数，增强随机性
    this.shuffleCount++;
    
    // 模拟共时性：根据时间、洗牌次数等因素增加随机性
    if (this.shuffleCount > 1) {
      // 额外随机化：随机交换一些卡片位置
      const extraShuffles = Math.floor(Math.random() * 5) + 1;
      for (let i = 0; i < extraShuffles; i++) {
        const idx1 = Math.floor(Math.random() * this.cards.length);
        const idx2 = Math.floor(Math.random() * this.cards.length);
        [this.cards[idx1], this.cards[idx2]] = [this.cards[idx2], this.cards[idx1]];
      }
    }
    
    this.isShuffled = true;
    this.drawnCards = []; // 重置已抽的牌
    
    return this.cards;
  }

  // 抽牌功能
  drawCard() {
    if (this.cards.length === 0) {
      throw new Error('牌组已空，请重新洗牌');
    }
    
    // 模拟共时性：根据当前状态调整抽牌概率
    let selectedIndex = 0;
    
    if (this.isShuffled && this.shuffleCount > 0) {
      // 使用加权随机选择，模拟共时性
      const weights = this.cards.map((_, index) => {
        // 基础权重
        let weight = 1;
        
        // 根据洗牌次数调整权重
        weight += this.shuffleCount * 0.1;
        
        // 根据时间因素调整权重
        const timeFactor = Date.now() % 1000 / 1000;
        weight += timeFactor * 0.5;
        
        // 根据已抽牌数量调整权重
        weight += this.drawnCards.length * 0.05;
        
        return weight;
      });
      
      // 加权随机选择
      const totalWeight = weights.reduce((sum, weight) => sum + weight, 0);
      let random = Math.random() * totalWeight;
      
      for (let i = 0; i < weights.length; i++) {
        random -= weights[i];
        if (random <= 0) {
          selectedIndex = i;
          break;
        }
      }
    } else {
      // 简单随机选择
      selectedIndex = Math.floor(Math.random() * this.cards.length);
    }
    
    const drawnCard = this.cards.splice(selectedIndex, 1)[0];
    
    // 随机决定正逆位
    const isReversed = Math.random() > 0.5;
    drawnCard.isReversed = isReversed;
    
    this.drawnCards.push(drawnCard);
    
    return drawnCard;
  }

  // 抽多张牌
  drawCards(count) {
    if (count > this.cards.length) {
      throw new Error(`牌组中只有${this.cards.length}张牌，无法抽取${count}张`);
    }
    
    const drawnCards = [];
    for (let i = 0; i < count; i++) {
      drawnCards.push(this.drawCard());
    }
    
    return drawnCards;
  }

  // 重置牌组
  reset() {
    this.cards = [...getAllCards()];
    this.drawnCards = [];
    this.isShuffled = false;
    this.shuffleCount = 0;
  }

  // 获取牌组状态
  getDeckStatus() {
    return {
      totalCards: getAllCards().length,
      remainingCards: this.cards.length,
      drawnCards: this.drawnCards.length,
      isShuffled: this.isShuffled,
      shuffleCount: this.shuffleCount
    };
  }

  // 获取已抽的牌
  getDrawnCards() {
    return [...this.drawnCards];
  }

  // 获取剩余牌数
  getRemainingCount() {
    return this.cards.length;
  }

  // 检查牌组是否为空
  isEmpty() {
    return this.cards.length === 0;
  }

  // 获取特定位置的牌（用于占卜阵型）
  getCardAtPosition(position) {
    if (position < 0 || position >= this.drawnCards.length) {
      return null;
    }
    return this.drawnCards[position];
  }

  // 重新洗牌并保持已抽的牌
  reshuffle() {
    // 保存已抽的牌
    const currentDrawn = [...this.drawnCards];
    
    // 重新洗牌
    this.shuffle();
    
    // 恢复已抽的牌
    this.drawnCards = currentDrawn;
    
    return this.cards;
  }
}

// 占卜阵型类
export class TarotSpread {
  constructor(name, positions) {
    this.name = name;
    this.positions = positions; // 位置描述数组
    this.cards = [];
  }

  // 为阵型抽牌
  drawForSpread(deck, cardCount) {
    if (cardCount !== this.positions.length) {
      throw new Error(`阵型需要${this.positions.length}张牌，但请求了${cardCount}张`);
    }
    
    this.cards = deck.drawCards(cardCount);
    return this.cards;
  }

  // 获取阵型解读
  getSpreadInterpretation() {
    if (this.cards.length === 0) {
      return '请先为阵型抽牌';
    }
    
    let interpretation = `\n${this.name}阵型解读：\n\n`;
    
    this.cards.forEach((card, index) => {
      const position = this.positions[index];
      const cardName = card.name;
      const isReversed = card.isReversed;
      const meaning = isReversed ? card.reversed.meaning : card.upright.meaning;
      
      interpretation += `${index + 1}. ${position}：${cardName}\n`;
      interpretation += `   状态：${isReversed ? '逆位' : '正位'}\n`;
      interpretation += `   含义：${meaning}\n\n`;
    });
    
    return interpretation;
  }

  // 获取阵型名称
  getName() {
    return this.name;
  }

  // 获取位置描述
  getPositions() {
    return [...this.positions];
  }
}

// 预定义占卜阵型
export const predefinedSpreads = {
  // 单张牌阵型
  singleCard: new TarotSpread('单张牌', ['当前状况']),
  
  // 三张牌阵型
  threeCard: new TarotSpread('三张牌', ['过去', '现在', '未来']),
  
  // 凯尔特十字阵型（简化版）
  celticCross: new TarotSpread('凯尔特十字', [
    '当前状况', '挑战', '过去', '未来', '内在', '外在',
    '希望与恐惧', '环境', '指引', '结果'
  ]),
  
  // 关系阵型
  relationship: new TarotSpread('关系阵型', [
    '你的现状', '对方现状', '关系基础', '关系发展', '建议'
  ]),
  
  // 事业阵型
  career: new TarotSpread('事业阵型', [
    '当前工作', '挑战', '机会', '建议', '结果'
  ])
}; 